package tk1.uebung3.restful;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import tk1.uebung3.model.Assortment;
import tk1.uebung3.model.ProductType;
import tk1.uebung3.model.ShoppingCart;
import tk1.uebung3.model.ShoppingCartContainer;

@Path("/buy/{cartid}/{productName}/{amount}")
public class Buy {


	@GET
	@Produces(MediaType.TEXT_PLAIN)
	public String buyProduct(@PathParam("cartid") String cartid, @PathParam("productName") String productName, @PathParam("amount") String amount){
		String response = "";
		
		ProductType productType = Assortment.getInstance().getProductTypeByName(productName);
		if(productType == null)
			return productName + "false";
		
		ShoppingCart cart = ShoppingCartContainer.getShoppingCart(cartid);
		if(cart == null)
			return "false";
		
		int amountToBuy = Integer.valueOf(amount).intValue();
		int amountAvailable = productType.getAvailableAmount();
		
		if(amountAvailable < amountToBuy)
			response = "false";
		else{
			boolean success = productType.purchase(amountToBuy);
			if(success){
				
				cart.addProduct(productType, amountToBuy);
				response = "true";
			}
		}
		return response;
	}
	

	
}
